


package jnpf.fico.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.xuyanwu.spring.file.storage.FileInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.vo.DownloadVO;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.config.ConfigValueUtil;
import jnpf.exception.DataException;
import jnpf.fico.entity.ZcglCwDebtCollectionLogEntity;
import jnpf.fico.model.debtcollectionlog.ZcglCwDebtCollectionLogForm;
import jnpf.fico.model.debtcollectionlog.ZcglCwDebtCollectionLogInfoVO;
import jnpf.fico.model.debtcollectionlog.ZcglCwDebtCollectionLogListVO;
import jnpf.fico.model.debtcollectionlog.ZcglCwDebtCollectionLogPagination;
import jnpf.fico.service.ZcglCwDebtCollectionLogService;
import jnpf.permission.entity.UserEntity;
import jnpf.util.*;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 *
 * ZcglCwDebtCollectionLog
 * @版本： V3.2.0
 * @版权： 智果云科技（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2024-10-26
 */
@Slf4j
@RestController
@Api(tags = "ZcglCwDebtCollectionLog" , value = "example")
@RequestMapping("/api/example/ZcglCwDebtCollectionLog")
public class ZcglCwDebtCollectionLogController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private ConfigValueUtil configValueUtil;

    @Autowired
    private UserProvider userProvider;


    @Autowired
    private ZcglCwDebtCollectionLogService zcglCwDebtCollectionLogService;



    /**
     * 列表
     *
     * @param zcglCwDebtCollectionLogPagination
     * @return
     */
    @ApiOperation("获取列表")
	@PostMapping("/getList")
    public ActionResult list(@RequestBody ZcglCwDebtCollectionLogPagination zcglCwDebtCollectionLogPagination)throws IOException{
        List<ZcglCwDebtCollectionLogEntity> list= zcglCwDebtCollectionLogService.getList(zcglCwDebtCollectionLogPagination);
        //处理id字段转名称，若无需转或者为空可删除

    List<ZcglCwDebtCollectionLogListVO> listVO=JsonUtil.getJsonToList(list,ZcglCwDebtCollectionLogListVO.class);
    for(ZcglCwDebtCollectionLogListVO zcglCwDebtCollectionLogVO:listVO){


                zcglCwDebtCollectionLogVO.setNotificationId_name(zcglCwDebtCollectionLogVO.getNotificationId());

                zcglCwDebtCollectionLogVO.setCustomerName_name(zcglCwDebtCollectionLogVO.getCustomerName());

                zcglCwDebtCollectionLogVO.setContractNo_name(zcglCwDebtCollectionLogVO.getContractNo());

                zcglCwDebtCollectionLogVO.setLeaseSpace_name(zcglCwDebtCollectionLogVO.getLeaseSpace());

                zcglCwDebtCollectionLogVO.setCollectionPrincipal_name(zcglCwDebtCollectionLogVO.getCollectionPrincipal());

                zcglCwDebtCollectionLogVO.setCollectionLateFee_name(zcglCwDebtCollectionLogVO.getCollectionLateFee());

                zcglCwDebtCollectionLogVO.setCreatortime_name(zcglCwDebtCollectionLogVO.getCreatortime());
        System.out.println("查看时间是多少"+zcglCwDebtCollectionLogVO.getCreatortime());
        //子表数据转换
     }

         PageListVO vo=new PageListVO();
         vo.setList(listVO);
         PaginationVO page=JsonUtil.getJsonToBean(zcglCwDebtCollectionLogPagination,PaginationVO.class);
         vo.setPagination(page);
         return ActionResult.success(vo);

    }

    /**
     * 创建
     *
     * @param zcglCwDebtCollectionLogForm
     * @return
     */
    @PostMapping
    @Transactional
    @ApiOperation("创建")
    public ActionResult create(@RequestBody @Valid ZcglCwDebtCollectionLogForm zcglCwDebtCollectionLogForm) throws DataException {
        boolean b =  zcglCwDebtCollectionLogService.checkForm(zcglCwDebtCollectionLogForm,0);
        if (b){
         return ActionResult.fail("单行输入不能重复");
        }
        String mainId =RandomUtil.uuId();

        UserInfo userInfo=userProvider.get();
		UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        ZcglCwDebtCollectionLogEntity entity = JsonUtil.getJsonToBean(zcglCwDebtCollectionLogForm, ZcglCwDebtCollectionLogEntity.class);
            entity.setId(mainId);
                zcglCwDebtCollectionLogService.save(entity);


        return ActionResult.success("创建成功");
}



    /**
    * 模板下载
    *
    * @return
    */
    @ApiOperation("模板下载")
    @GetMapping("/TemplateDownload")
    public ActionResult<DownloadVO>  TemplateDownload(){
        UserInfo userInfo=userProvider.get();
        DownloadVO vo=DownloadVO.builder().build();
        try{
            vo.setName("职员信息.xlsx");
            vo.setUrl(UploaderUtil.uploaderFile("/api/Common/DownloadModel?encryption=" ,userInfo.getId()+"#"+"职员信息.xlsx"+"#"+"Temporary"));
        }catch(Exception e){
            log.error("信息导出Excel错误:{}" ,e.getMessage());
        }
        return ActionResult.success(vo);
    }

    /**
    * 导出Excel
    *
    * @return
    */
    @ApiOperation("导出Excel")
    @PostMapping("/Actions/Export")
    public ActionResult Export(@RequestBody ZcglCwDebtCollectionLogPagination zcglCwDebtCollectionLogPagination) throws IOException {
        if (StringUtil.isEmpty(zcglCwDebtCollectionLogPagination.getSelectKey())){
            return ActionResult.fail("请选择导出字段");
        }
        List<ZcglCwDebtCollectionLogEntity> list = zcglCwDebtCollectionLogService.getTypeList(zcglCwDebtCollectionLogPagination,zcglCwDebtCollectionLogPagination.getDataType());
        //处理id字段转名称，若无需转或者为空可删除

    List<ZcglCwDebtCollectionLogListVO> listVO=JsonUtil.getJsonToList(list,ZcglCwDebtCollectionLogListVO.class);
    for(ZcglCwDebtCollectionLogListVO zcglCwDebtCollectionLogVO:listVO){
                zcglCwDebtCollectionLogVO.setNotificationId_name(zcglCwDebtCollectionLogVO.getNotificationId());

                zcglCwDebtCollectionLogVO.setCustomerName_name(zcglCwDebtCollectionLogVO.getCustomerName());

                zcglCwDebtCollectionLogVO.setContractNo_name(zcglCwDebtCollectionLogVO.getContractNo());

                zcglCwDebtCollectionLogVO.setLeaseSpace_name(zcglCwDebtCollectionLogVO.getLeaseSpace());

                zcglCwDebtCollectionLogVO.setCollectionPrincipal_name(zcglCwDebtCollectionLogVO.getCollectionPrincipal());

                zcglCwDebtCollectionLogVO.setCollectionLateFee_name(zcglCwDebtCollectionLogVO.getCollectionLateFee());

                zcglCwDebtCollectionLogVO.setCreatortime_name(zcglCwDebtCollectionLogVO.getCreatortime());

		//子表数据转换
     }

        //转换为map输出
        List<Map<String, Object>>mapList=JsonUtil.getJsonToListMap(JsonUtil.getObjectToStringDateFormat(listVO,"yyyy-MM-dd HH:mm:ss"));
            mapList.stream().forEach(map -> {
            Map<String,Object> map2 =new HashMap<>();
            map.putAll(map2);
            });
        String[]keys=!StringUtil.isEmpty(zcglCwDebtCollectionLogPagination.getSelectKey())?zcglCwDebtCollectionLogPagination.getSelectKey().split(","):new String[0];
        UserInfo userInfo=userProvider.get();
        DownloadVO vo=this.creatModelExcel(configValueUtil.getTemporaryFilePath(),mapList,keys,userInfo);
        return ActionResult.success(vo);
    }
    //导出表格
    public DownloadVO creatModelExcel(String path,List<Map<String, Object>>list,String[]keys,UserInfo userInfo){
        DownloadVO vo=DownloadVO.builder().build();
            List<ExcelExportEntity> entitys=new ArrayList<>();
            if(keys.length>0){
                for(String key:keys){
                    switch(key){
                    case "notificationId" :
                    entitys.add(new ExcelExportEntity("通知单编号" ,"notificationId_name"));
                    break;
                    case "customerName" :
                    entitys.add(new ExcelExportEntity("客户名称" ,"customerName_name"));
                    break;
                    case "contractNo" :
                    entitys.add(new ExcelExportEntity("合同编号" ,"contractNo_name"));
                    break;
                    case "leaseSpace" :
                    entitys.add(new ExcelExportEntity("租凭空间" ,"leaseSpace_name"));
                    break;
                    case "collectionPrincipal" :
                    entitys.add(new ExcelExportEntity("催款本金" ,"collectionPrincipal_name"));
                    break;
                    case "collectionLateFee" :
                    entitys.add(new ExcelExportEntity("催款滞纳金" ,"collectionLateFee_name"));
                    break;
                    case "creatortime" :
                    entitys.add(new ExcelExportEntity("创建时间" ,"creatortime_name"));
                    break;
            default:
                    break;

                    }
                }
				List<String> keylist = new ArrayList<>();
				for (String key:keys){
				    keylist.add(key);
				}
            }

        ExportParams exportParams = new ExportParams(null, "表单信息");
        exportParams.setType(ExcelType.XSSF);
        try{
		@Cleanup Workbook workbook = new HSSFWorkbook();
        if (entitys.size()>0){
            if (list.size()==0){
				list.add(new HashMap<>());
            }
            workbook = ExcelExportUtil.exportExcel(exportParams, entitys, list);
        }
        String fileName = "表单信息" + DateUtil.dateNow("yyyyMMdd") + "_" + RandomUtil.uuId() + ".xlsx";

        String temporaryFilePath = configValueUtil.getTemporaryFilePath();
        MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
        FileInfo fileInfo = FileUploadUtils.uploadFile(multipartFile, temporaryFilePath, fileName);
        vo.setName(fileInfo.getFilename());
        vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
        } catch (Exception e) {
            log.error("信息导出Excel错误:{}", e.getMessage());
            e.printStackTrace();
        }
        return vo;
    }



    /**
    * 信息
    *
    * @param id
    * @return
    */
    @ApiOperation("信息")
    @GetMapping("/{id}")
    public ActionResult<ZcglCwDebtCollectionLogInfoVO> info(@PathVariable("id") String id){
        ZcglCwDebtCollectionLogEntity entity= zcglCwDebtCollectionLogService.getInfo(id);
        ZcglCwDebtCollectionLogInfoVO vo=JsonUtil.getJsonToBean(entity, ZcglCwDebtCollectionLogInfoVO.class);

    //子表
    //副表
        return ActionResult.success(vo);
    }

    /**
    * 表单信息(详情页)
    *
    * @param id
    * @return
    */
    @ApiOperation("表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult<ZcglCwDebtCollectionLogInfoVO> detailInfo(@PathVariable("id") String id){
        ZcglCwDebtCollectionLogEntity entity= zcglCwDebtCollectionLogService.getInfo(id);
        ZcglCwDebtCollectionLogInfoVO vo=JsonUtil.getJsonToBean(entity, ZcglCwDebtCollectionLogInfoVO.class);

 //子表数据转换

 //附表数据转换

//添加到详情表单对象中
                vo.setNotificationId(vo.getNotificationId());

                vo.setCustomerName(vo.getCustomerName());

                vo.setContractNo(vo.getContractNo());

                vo.setLeaseSpace(vo.getLeaseSpace());

                vo.setCollectionPrincipal(vo.getCollectionPrincipal());

                vo.setCollectionLateFee(vo.getCollectionLateFee());

                vo.setCreatortime(vo.getCreatortime());


        return ActionResult.success(vo);
		}




   /**
    * 更新
    *
    * @param id
    * @param zcglCwDebtCollectionLogForm
    * @return
    */
    @PutMapping("/{id}")
    @Transactional
    @ApiOperation("更新")
    public ActionResult update(@PathVariable("id") String id,@RequestBody @Valid ZcglCwDebtCollectionLogForm zcglCwDebtCollectionLogForm) throws DataException {
        boolean b =  zcglCwDebtCollectionLogService.checkForm(zcglCwDebtCollectionLogForm,1);
        if (b){
         return ActionResult.fail("单行输入不能重复");
        }
        UserInfo userInfo=userProvider.get();
        ZcglCwDebtCollectionLogEntity entity= zcglCwDebtCollectionLogService.getInfo(id);
        if(entity!=null){
            ZcglCwDebtCollectionLogEntity subentity=JsonUtil.getJsonToBean(zcglCwDebtCollectionLogForm, ZcglCwDebtCollectionLogEntity.class);
				boolean b1 = zcglCwDebtCollectionLogService.updateById(subentity);
				if (!b1){
				return ActionResult.fail("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
				}
        return ActionResult.success("更新成功");
        }else{
            return ActionResult.fail("更新失败，数据不存在");
        }
    }



   /**
    * 删除
    *
    * @param id
    * @return
    */
    @ApiOperation("删除")
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id){
        ZcglCwDebtCollectionLogEntity entity= zcglCwDebtCollectionLogService.getInfo(id);
        if(entity!=null){
            zcglCwDebtCollectionLogService.delete(entity);

        }
        return ActionResult.success("删除成功");
    }











}
